package com.kaf.ai.service.impl;

import com.kaf.ai.config.AiConfig;
import com.kaf.ai.constant.AiProvider;
import com.kaf.ai.dto.AiRequest;
import com.kaf.ai.dto.AiResponse;
import com.kaf.ai.service.AiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Service
public class TongyiAiServiceImpl{

    private final WebClient webClient;
    private final AiConfig.AiProperties properties;

    public TongyiAiServiceImpl(WebClient webClient,
                               @Autowired(required = false) AiConfig aiConfig) {
        this.webClient = webClient;
        this.properties = aiConfig != null ? aiConfig.tongyiProperties() : new AiConfig.AiProperties();
    }

    public Mono<AiResponse> generateResponse(AiRequest request) {
        log.info("调用 通义千问 模型: {}, prompt: {}", properties.getModel(), request.getPrompt());

        return webClient.post()
                .uri(properties.getBaseUrl() + "/services/aigc/text-generation/generation")
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + properties.getApiKey())
                .header("X-DashScope-SSE", "enable") // 如需流式
                .header(HttpHeaders.CONTENT_TYPE, "application/json")
                .bodyValue(buildRequestBody(request))
                .retrieve()
                .bodyToMono(TongyiResponse.class)
                .map(this::convertToAiResponse)
                .onErrorResume(e -> {
                    log.error("通义千问调用失败", e);
                    return Mono.just(AiResponse.error("调用通义失败: " + e.getMessage(), AiProvider.TONGYI.name()));
                });
    }

    private Object buildRequestBody(AiRequest request) {
        return new RequestBody(
                properties.getModel(),
                request.getPrompt()
        );
    }

    private AiResponse convertToAiResponse(TongyiResponse resp) {
        if (resp == null || resp.getOutput() == null) {
            return AiResponse.error("返回结果为空", AiProvider.TONGYI.name());
        }
        String content = resp.getOutput().getText();
        return AiResponse.success(content, properties.getModel(), AiProvider.TONGYI.name());
    }

    private static class RequestBody {
        private String model;
        private String input;

        public RequestBody(String model, String input) {
            this.model = model;
            this.input = input;
        }
        public String getModel() { return model; }
        public String getInput() { return input; }
    }

    private static class TongyiResponse {
        private Output output;

        public Output getOutput() { return output; }

        static class Output {
            private String text;
            public String getText() { return text; }
        }
    }
}